package com.service.oos;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import com.common.spring.SpringMvcUtils; 
import com.dao.oos.OosDataDao;
import com.model.oos.OosDataModel;
import com.model.sys.SysUser;
import com.service.sys.WXService;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.oos.OosTaskDao;
import com.model.oos.OosTaskModel;
import com.common.model.Global;

@Service
public class OosTaskService {
    static final Logger logger = LoggerFactory.getLogger(OosTaskService.class);

    @Autowired
    OosTaskDao oosTaskDao;

    @Autowired
    OosDataDao oosDataDao;
	@Autowired
	WXService wxService;

    /**
     * 列表查询
     *
     * @param queryMap
     * @return
     */
    public HttpResult selectList(Map<String, Object> queryMap) {
        HttpResult httpResult = new HttpResult();
        EasyuiUtils.addPageNum(queryMap);
        EasyuiUtils.addFilter(queryMap);
        List<OosTaskModel> list = oosTaskDao.selectList(queryMap);
        int count = oosTaskDao.selectListCount(queryMap);
        httpResult.setRows(list);
        httpResult.setTotal(count);
        logger.info("selectList:{}", list);
        return httpResult;
    }

    /**
     * 列表查询(由部门权限的)
     *
     * @param queryMap
     * @return
     */
    public HttpResult selectListDutyDept(Map<String, Object> queryMap) {
        HttpResult httpResult = new HttpResult();
        SysUser sysUser = SpringMvcUtils.getSysUser();
        // 只查询属于当前登录人部门的task
        if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
            if (StringUtils.isNotNull(sysUser.getDatapermission())) {
                String[] datapermission = sysUser.getDatapermission().split(",");
                if (ArrayUtils.contains(datapermission, sysUser.getDeptid())) {
                    queryMap.put("executDeptCode", sysUser.getDeptid());
                } else {
                    queryMap.put("executor", sysUser.getLoginname());
                }
            } else {
                queryMap.put("executor", sysUser.getLoginname());
            }
        }
        List<OosTaskModel> list = oosTaskDao.selectListByOsId(queryMap);
        httpResult.setData(list);
        logger.info("selectList:{}", list);
        return httpResult;
    }

    /**
     * 详情
     *
     * @param
     * @return
     */
    public HttpResult selectInfor(String taskId) {
        HttpResult httpResult = new HttpResult();
        OosTaskModel oosTaskModel = oosTaskDao.load(taskId);
        httpResult.setData(oosTaskModel);
        httpResult.setCode(HttpStatus.SUCCESS_CODE);
        return httpResult;
    }

    /**
     * 保存
     *
     * @param
     * @return
     */
    public HttpResult save(OosTaskModel oosTaskModel) {
        if (oosTaskModel == null) {
            return HttpResult.error("参数不能为空");
        }
        HttpResult httpResult = new HttpResult();
        int result = 0;
        if (!StringUtils.isNotNull(oosTaskModel.getTaskId())) {
            oosTaskModel.setTaskId(UUID.randomUUID().toString());
            result = oosTaskDao.insert(oosTaskModel);
        } else {
            result = oosTaskDao.update(oosTaskModel);
        }
        if (result > 0) {
            httpResult.setMsg(oosTaskModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
            httpResult.setData(oosTaskModel);
        } else {
            httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            httpResult.setMsg(oosTaskModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
        }
        return httpResult;
    }

    /**
     * 退回行动项
     *
     * @param taskId
     * @return
     */
    public int backUp(String taskId) throws IOException { 
        OosTaskModel oosTaskModel = oosTaskDao.load(taskId);
        int result = 0;
        if (null != oosTaskModel) {
          OosDataModel oosDataModel = oosDataDao.load(oosTaskModel.getOsId());
            result = oosTaskDao.backUp(taskId);
            if (result >0) {
            	wxService.sendTxtMessage(oosTaskModel.getExecutor(), "【OOS提醒消息】您好，编号："+oosDataModel.getOsCode()+"的OOS项目中，您的部门自查项被退回，请登录CMP查看。");
            }
        }
        return result;
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    public HttpResult delete(String taskId) {
        HttpResult httpResult = new HttpResult();
        if (!StringUtils.isNotNull(taskId)) {
            return HttpResult.error("参数不能为空");
        }
        int result = oosTaskDao.delete(taskId);
        if (result > 0) {
            httpResult.setMsg("删除成功！");
        } else {
            httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
            httpResult.setMsg("不存在此条数据！");
        }
        return httpResult;
    }

    /**
     * 导出
     *
     * @param queryMap
     * @param response
     */
    public void export(Map<String, Object> queryMap, HttpServletResponse response) {
        List<OosTaskModel> list = oosTaskDao.selectList(queryMap);
        logger.info("export:{}", list);
        try {
            EasyExcel.write(response.getOutputStream(), OosTaskModel.class).sheet("模板").doWrite(list);
        } catch (IOException e) {
            logger.error("导出错误:{}", e.getMessage());
        }

    }
}
